package com.gdut.file;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FileActivity extends AppCompatActivity {

    private Toolbar mToolbar;
    private ListView mFileListView;
    private FileAdapter mFileAdapter;
    private List<String> mFileList;
    private String mParentPath;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file);
        initToolbar();
        initListView();
        getPermission();
    }

    private void initToolbar() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }
    }

    private void initListView() {
        mFileListView = (ListView) findViewById(R.id.file_list);
        mFileList = new ArrayList<>();
        mFileAdapter = new FileAdapter(this, mFileList);
        mFileListView.setAdapter(mFileAdapter);
        View headerView = LayoutInflater.from(this).inflate(R.layout.layout_header_view, mFileListView, false);
        mFileListView.addHeaderView(headerView);
        mFileListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == 0) {
                    backward();
                    return;
                }
                String select = (String) adapterView.getAdapter().getItem(i);
//                Toast.makeText(FileActivity.this, select, Toast.LENGTH_LONG).show();
                forward(select);
            }
        });
    }

    private static final int EXTERNAL_STORAGE_PERMISSION_CODE = 1000;

    private void getPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(FileActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    EXTERNAL_STORAGE_PERMISSION_CODE);
        } else {
            loadData();
        }
    }

    private void loadData() {
        if (getIntent() != null) {
            mParentPath = getIntent().getStringExtra("path");
        } else {
            mParentPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        }
        File file = new File(mParentPath);
        loadDir(file);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == EXTERNAL_STORAGE_PERMISSION_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                loadData();
            } else {
                Toast.makeText(FileActivity.this, "未授权", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_select, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_select) {
            Intent intent = new Intent();
            intent.putExtra("data", mParentPath);
            setResult(RESULT_OK, intent);
            finish();
        }
        return true;
    }

    @Override
    public void onBackPressed() {
        backward();
    }

    private void forward(String next) {
        String forwardPath = mParentPath + File.separator + next;
        File sub = new File(forwardPath);
        loadDir(sub);
    }

    private void backward() {
        File file = new File(mParentPath);
        File parent = file.getParentFile();
        loadDir(parent);
    }

    private void loadDir(File file) {
        if (file != null && file.isDirectory()) {
            mToolbar.setTitle(file.getName());
            File[] files = file.listFiles(new FileFilter() {
                @Override
                public boolean accept(File file) {
                    return file.isDirectory() && !file.getName().startsWith(".");
                }
            });
            if (files == null) {
                return;
            }
            List<String> paths = new ArrayList<>();
            for (File temp : files) {
                paths.add(temp.getName());
            }
            Collections.sort(paths);
            mParentPath = file.getAbsolutePath();
            mFileList.clear();
            mFileList.addAll(paths);
            mFileAdapter.notifyDataSetChanged();
        }
    }

    public static void startActivityForResult(Activity activity, String path, int reauestCode) {
        Intent intent = new Intent(activity, FileActivity.class);
        intent.putExtra("path", path);
        activity.startActivityForResult(intent, reauestCode);
    }
}
